package com.zhugang.week04;

/**
 * @program algorithms
 * @description: smallestK
 * @author: chanzhugang
 * @create: 2022/06/30 17:39
 */
public class SmallestK2 {

    public static void main(String[] args) {
        SmallestK2 smallestK2 = new SmallestK2();
        int[] arr = new int[]{1, 3, 5, 7, 2, 4, 6, 8};
        int[] result = smallestK2.smallestK(arr, 4);
        for (int r : result) {
            System.out.println(r);
        }

    }

    /**
     * 最小K个数
     *
     * @param arr
     * @param k
     * @return
     */

    private int[] res;
    private int count = 0;

    public int[] smallestK(int[] arr, int k) {
        // 快排思路
        res = new int[k];
        quickSort(arr, 0, arr.length - 1, k);
        return res;
    }

    private void quickSort(int[] arr, int p, int r, int k) {
        if (p > r) {
            return;
        }
        // 分区点下标
        int q = partition(arr, p, r);
        if (q - p + 1 == k) {
            // 前K个元素放入数组
            for (int i = p; i <= q; i++) {
                res[count++] = arr[i];
            }
        } else if (q - p + 1 < k) {
            for (int i = p; i < q; i++) {
                res[count++] = arr[i];
            }
            quickSort(arr, q + 1, r, k - (q - p + 1));
        } else {
            quickSort(arr, p, q - 1, k);
        }
    }

    private int partition(int[] arr, int p, int r) {
        int i = p - 1;
        int j = p;
        while (j < r) {
            if (arr[j] < arr[r]) {
                swap(arr, i + 1, j);
                i++;
            }
            j++;
        }
        swap(arr, i + 1, r);
        return i + 1;
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}